package com.example.demo.controller;


import com.example.demo.entity.user.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户中心")
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 身份认证测试接口
     * @param request
     * @return
     */
    @GetMapping("/admin")
    @ApiResponses(@ApiResponse(code = 200,message = "OK"))
    @ApiOperation(value = "管理员接口",response = String.class)
    public String admin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        return user.getUsername();
    }

    /**
     * 角色认证测试接口
     * @param request
     * @return
     */
    @RequiresPermissions("student:*")
    @GetMapping("/student")
    @ApiResponses(@ApiResponse(code = 200,message = "OK"))
    @ApiOperation(value = "学生接口",response = String.class)
    public String student(HttpServletRequest request) {
        return "success";
    }

    /**
     * 权限认证测试接口
     * @param request
     * @return
     */
    @RequiresRoles("teacher")
    @GetMapping("/teacher")
    @ApiResponses(@ApiResponse(code = 200,message = "OK"))
    @ApiOperation(value = "老师接口",response = String.class)
    public String teacher(HttpServletRequest request) {
        return "success";
    }


    /**
     * 用户登录接口
     * @param user user
     * @param request request
     * @return string
     */
    @PostMapping("/login")
    @ApiResponses(@ApiResponse(code = 200,message = "OK"))
    @ApiOperation(value = "登录接口",response = String.class)
    public String login(User user, HttpServletRequest request) {

        // 根据用户名和密码创建 Token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        // 获取 subject 认证主体
        Subject subject = SecurityUtils.getSubject();
        try{
            // 开始认证，这一步会跳到我们自定义的 Realm 中
            subject.login(token);
            request.getSession().setAttribute("user", user);
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            request.getSession().setAttribute("user", user);
            request.setAttribute("error", "用户名或密码错误！");
            return "login";
        }
    }

}
